package org.e_gold.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.e_gold.dao.CEventDAO;
import org.e_gold.model.crawler.livescore.CEvent;
import org.e_gold.service.CEventService;
import org.e_gold.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author Thang Nguyen
 */
@Service
public class CEventServiceImpl implements CEventService {

	private static final Logger logger = Logger.getLogger(CEventServiceImpl.class);

	@Autowired
	private CEventDAO cEventDAO;

	@Override
	public void saveEvent(List<CEvent> lstCEvent) {
		try{
			if(CollectionUtils.isEmpty(lstCEvent)){
				logger.error("empty list");
			}else{
				List<CEvent> lstCurrent = getNearlyCEvent();
				for(int i = 0; i < lstCEvent.size(); i++){
					CEvent c = lstCEvent.get(i);
					if(!lstCurrent.contains(c)){
						//						System.out.println("<<<<<<<<<<<<<<<<Added: " + c);
						cEventDAO.insert(c);
					}else{
						//						System.out.println("<<<<<<<<<<<<<<<<equals: " + c);
					}
				}
			}
		}catch(Exception ex){
			logger.info(ex.getMessage());
			logger.error(ex);
			ex.printStackTrace();
		}
	}

	@Override
	public void insert(CEvent cEvent) {
		try{
			CEvent example = new CEvent(cEvent.getHomeName(), cEvent.getAwayName(), cEvent.getLeague());
			List<CEvent> lst = cEventDAO.findByExample(example);
			if(CollectionUtils.isEmpty(lst)){
				cEventDAO.insert(example);
			}
		}catch(Exception ex){
			logger.info(ex.getMessage());
			logger.error(ex);
			ex.printStackTrace();
		}
	}

	@Override
	public List<CEvent> getNearlyCEvent() {
		try{
			Date[] eventDateRange = DateUtil.getDateInRange(1);

			return cEventDAO.getCEventInRange(eventDateRange[0], eventDateRange[1]);
		}catch(Exception ex){
			logger.info(ex.getMessage());
			logger.error(ex);
			ex.printStackTrace();
		}
		return null;
	}

	@Override
	public CEvent getEventByHomeAndAwayName(String home_name, String away_name) {
		try{
			CEvent c = new CEvent(home_name, away_name);
			List<CEvent> lst = cEventDAO.findByExample(c, new String[]{"id", "league", "play_date", "status"});
			if(!CollectionUtils.isEmpty(lst)){
				return lst.get(0);
			}
		}catch(Exception ex){
			logger.info(ex.getMessage());
			logger.error(ex);
			ex.printStackTrace();
		}
		return null;
	}
}
